package advance.juc.executor;

import advance.util.StringUtils;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Name thread factory.
 */
public class NameThreadFactory implements ThreadFactory {

    /**
     * 线程名称数字后缀编号
     */
    private final AtomicInteger id = new AtomicInteger(0);

    /**
     * 线程名称前缀
     */
    private String name;

    /**
     * 构造方法
     * @param name 不能以"."结尾
     */
    public NameThreadFactory(String name) {
        if (!name.endsWith(StringUtils.DOT)) {
            name += StringUtils.DOT;
        }
        this.name = name;
    }

    @Override
    public Thread newThread(Runnable r) {
        String threadName = name + id.getAndDecrement();
        Thread thread = new Thread(r, threadName);
        thread.setDaemon(true);
        return thread;
    }
}
